class Tolltip {
  mousemoveCallback = (...args) => this.mousemove(...args);
  messageBox = undefined;
  supportInstance = undefined;

  bind(supportInstance) {
    this.supportInstance = supportInstance;
    document.body.removeEventListener('mousemove', this.mousemoveCallback);
    document.body.addEventListener('mousemove', this.mousemoveCallback);
  }

  mousemove(e) {
    let {target, clientX, clientY} = e;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = undefined;
    }
    this.timer = setTimeout(() => {
      if (this.isInTooltip(target)) {
        return;
      }
      if (this.isFormulaIcon(target)) {
        this.showMessageBox(target, clientX, clientY);
      } else {
        this.hideBox();
      }
    }, 260);
  }

  isInTooltip(target) {
    while (target && target !== document.body && !target.classList.contains('h-flow-editor-tooltip')) {
      target = target.parentNode;
    }
    return target && target !== document.body && target.classList.contains('h-flow-editor-tooltip');
  }

  isFormulaIcon(target) {
    return target.classList.contains('h-flow-formula-icon');
  }

  hideBox() {
    if (this.messageBox) {
      this.messageBox.remove();
    }
    this.messageBox = undefined;
  }

  showMessageBox(target, clientX, clientY) {
    if (!this.messageBox) {
      this.createMessageBox();
    }
    this.messageBox.innerHTML = '';
    this.messageBox.style.left = (clientX - 80) + 'px';
    this.messageBox.style.top = (clientY + 30) + 'px';
    this.createContent(target).forEach(e => this.messageBox.append(e));
  }

  createContent(el) {
    let id = this.supportInstance.getNodeId(el);
    let {edges} = this.supportInstance.getModel();
    let edge = (edges || []).find(e => e.id === id);
    if (!edge) {
      throw new Error("没有找到边：" + id);
    }
    return [
      this.createTitle('分支条件:'),
      this.createMessage(edge.formulaText),
      this.createTitle('分支优先级:'),
      this.createMessage(edge.priority + ' (数字越大越优先执行)'),
    ];
  }

  createMessage(text) {
    let div = document.createElement('div');
    div.innerHTML = text;
    div.className = 'h-flow-editor-tooltip-message';
    return div;
  }

  createTitle(text) {
    let div = document.createElement('div');
    div.innerHTML = text;
    div.className = 'h-flow-editor-tooltip-title';
    return div;
  }

  createMessageBox() {
    this.messageBox = document.createElement('div');
    document.body.append(this.messageBox);
    this.messageBox.className = 'h-flow-editor-tooltip';
  }
}

export default new Tolltip();